﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExplorerPlus.DomainObjects;
using ExplorerPlus.PluginsInterface;
using ExplorerPlus.Plugins.Common;

namespace ExplorerPlus.Plugins.Music
{
    public partial class MusicItemDetailView : UserControl, IItemDetailViewPlugin
    {
        //Control object responsible for rating movie titles.  
        //Workaround: project cannot dynamically build this custom control type
        //                      after using New Project wizard; the control instance is created and sited at runtime instead of 
        //                      adding to design surface.  
        internal ExplorerPlus.Controls.RatingPickerControl ratingPickerControl =
            new ExplorerPlus.Controls.RatingPickerControl();

        Item album;
        bool blnHasChanges = false;

        public MusicItemDetailView()
        {
            InitializeComponent();

            this.webBrowser1.AllowNavigation = false;
            this.webBrowser1.AllowWebBrowserDrop = false;
            this.webBrowser1.WebBrowserShortcutsEnabled = false;
        }

        #region IItemDetailViewPlugin Members

        UserControl IItemDetailViewPlugin.ItemDetailView
        {
            get { return this; }
        }

        bool IItemDetailViewPlugin.HasChanges
        {
            get { return blnHasChanges; }
            set { blnHasChanges = value; }
        }

        void IItemDetailViewPlugin.Initialize(Item item)
        {
            album = item;
            SetAlbum();
        }

        Item IItemDetailViewPlugin.GetItem()
        {
            GetAlbum();
            return album;
        }

        bool IItemDetailViewPlugin.Validate()
        {
            if (txtTitle.Text == string.Empty || txtTitle.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please enter album title.");
                return false;
            }

            return true;
        }

        Item IItemDetailViewPlugin.Store()
        {
            GetAlbum();
            blnHasChanges = false;
            new MusicWebSearchPlugin().DownloadItemImages(album, Application.StartupPath + "\\Images\\Music\\");
            return album;
        }

        void IItemDetailViewPlugin.DragDropFile(string[] filePath)
        {
            album.FilePath = filePath[0];
            txtFilePath.Text = album.FilePath;
        }

        #endregion

        private void SetAlbum()
        {
            txtTitle.Text = album.ItemName;
            txtFilePath.Text = album.FilePath;
            txtArtist.Text = album.GetItemPropertyValue((int)MusicFields.Artist);
            txtStyle.Text = album.GetItemPropertyValue((int)MusicFields.Style);
            txtMusicCompany.Text = album.GetItemPropertyValue((int)MusicFields.Manufacturer);
            txtReleaseDate.Text = album.GetItemPropertyValue((int)MusicFields.ReleaseDate);
            txtEdition.Text = album.GetItemPropertyValue((int)MusicFields.Edition);
            txtBinding.Text = album.GetItemPropertyValue((int)MusicFields.Binding);
            txtSalesRank.Text = album.GetItemPropertyValue((int)MusicFields.SalesRank);
            txtListPrice.Text = album.GetItemPropertyValue((int)MusicFields.ListPrice);
            pictureBox1.ImageLocation = album.GetItemPropertyValue((int)MusicFields.LargeImage);
            if (webBrowser1.Document != null)
            {
                webBrowser1.Document.Body.InnerHtml =
                    "<html><body  style='font-family:Tahoma; font-size=10pt'>"
                        + album.GetItemPropertyValue((int)MusicFields.EditorialReviews)
                        + "</body></html>";
            }
            else
            {
                webBrowser1.DocumentText =
                    "<html><body  style='font-family:Tahoma; font-size=10pt'>"
                    + album.GetItemPropertyValue((int)MusicFields.EditorialReviews)
                    + "</body></html>";
            }
            SetRating();
            RegisterValueChangesEvent(this);
        }

        private void GetAlbum()
        {
            album.ItemName = txtTitle.Text;
            album.FilePath = txtFilePath.Text;
            PluginHelper.ExtractValueList(album, (int)MusicFields.Artist, txtArtist.Text);
            PluginHelper.ExtractValueList(album, (int)MusicFields.Style, txtStyle.Text);
            album.SetItemPropertyValue((int)MusicFields.Manufacturer, txtMusicCompany.Text);
            album.SetItemPropertyValue((int)MusicFields.ReleaseDate, txtReleaseDate.Text);
            album.SetItemPropertyValue((int)MusicFields.Edition, txtEdition.Text);
            album.SetItemPropertyValue((int)MusicFields.ListPrice, txtListPrice.Text);
            album.SetItemPropertyValue((int)MusicFields.Binding, txtBinding.Text);
            album.SetItemPropertyValue((int)MusicFields.Rating, ratingPickerControl.CurrentRating.ToString());
            album.SetItemPropertyValue((int)MusicFields.SalesRank, txtSalesRank.Text);
        }

        #region Register form controls editing
        private void RegisterValueChangesEvent(Control ctl)
        {
            if (ctl.HasChildren)
            {
                foreach (Control child in ctl.Controls)
                {
                    RegisterValueChangesEvent(child);
                }
            }
            else
                RegisterControlGenericEvent(ctl);
        }

        private void RegisterControlGenericEvent(Control ctl)
        {
            if (ctl is Label)
                return;
            else if (ctl is TextBox || ctl is ComboBox || ctl is DateTimePicker)
            {
                ctl.TextChanged += new EventHandler(ctl_TextChanged);
                return;
            }
            else if (ctl is RadioButton)
            {
                ((RadioButton)ctl).CheckedChanged += new EventHandler(ctl_TextChanged);
            }
        }

        void ctl_TextChanged(object sender, EventArgs e)
        {
            blnHasChanges = true;
        }
        #endregion

        private void lnkVisitPage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.VisitPage(album.GetItemPropertyValue((int)MusicFields.DetailPageUrl));
        }

        private void lnkOpenFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.OpenFile(album.FilePath);
        }

        private void lnkOpenDirectory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.OpenDirectory(album.FilePath);
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
                album.FilePath = openFileDialog1.FileName;
            }
        }

        /// <summary>
        /// Initializes the rating picker control used on this user control.  
        /// </summary>
        /// <remarks>
        /// Called by ListDetails.Load event.  This special initialization code is not required if the 
        /// RatingPickerControl is built and referenced in a separate control library.  
        /// </remarks>
        private void InitRatingPickerControl()
        {
            //create rating picker control object and site it on the parent user control
            this.panel3.Controls.Add(this.ratingPickerControl);
            //set default properties and data binding
            ((System.ComponentModel.ISupportInitialize)this.ratingPickerControl).BeginInit();
            this.ratingPickerControl.Anchor = (System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
            this.ratingPickerControl.BackColor = System.Drawing.Color.Transparent;
            this.ratingPickerControl.Location = new System.Drawing.Point(55, 216);
            this.ratingPickerControl.Name = "RatingPickerControl1";
            this.ratingPickerControl.Size = new System.Drawing.Size(80, 16);
            this.ratingPickerControl.TabIndex = 1;
            ((System.ComponentModel.ISupportInitialize)this.ratingPickerControl).EndInit();
        }

        private void SetRating()
        {
            if (ratingPickerControl != null)
            {
                string rating = album.GetItemPropertyValue((int)MusicFields.Rating);
                if (rating != string.Empty || rating != "")
                {
                    double result = -1;
                    if (double.TryParse(rating, out result))
                    {
                        this.ratingPickerControl.CurrentRating = (int)result;
                    }
                }
                else
                {
                    this.ratingPickerControl.CurrentRating = -1;
                }
            }

            string customerRating =
                album.GetItemPropertyValue((int)MusicFields.TotalCustomerReviews);

            if (customerRating != string.Empty || customerRating != "")
            {
                this.lblCustomerReviews.Text = "(" + customerRating + ")";
            }
        }

        private void MusicItemDetailView_Load(object sender, EventArgs e)
        {
            //dynamically create rating picker control and site on the form
            InitRatingPickerControl();
        }

        private void lnkTracks_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (album.GetItemPropertyValue((int)MusicFields.Track).Length > 0)
            {
                using (AlbumTracks form = new AlbumTracks())
                {
                    IEnumerable<Item.ItemProperty> enumerator =
                        album.GetItemPropertyEnumerator((int)MusicFields.Track);

                    foreach (Item.ItemProperty itemProp in enumerator)
                    {
                        string[] fields = itemProp.ItemPropertyValue.Split('#');
                        form.lstItems.Items.Add(
                            new ListViewItem(fields));
                    }

                    form.lstItems.ResizeColumns();

                    form.ShowDialog();
                }
            }
        }

    }
}
